package com.freecloud.javabasics.thread.simple;

import com.freecloud.common.LoggerUtil;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * 主动取消、停止线程
 * @Author: maomao
 * @Date: 2021-03-24 09:57
 */
public class CancelThreadTest {

    public static void main(String[] args) throws Exception {
        PrimeGenerator generator = new PrimeGenerator();

        new Thread(generator).start();
        try {
            Thread.sleep(1000);
        }finally {
            generator.cancel();
        }

        LoggerUtil.printThread(generator.get().toString());
    }

    public static class PrimeGenerator implements Runnable{

        private final List<BigInteger> primes = new ArrayList<>();
        private volatile boolean cancelled;

        @Override
        public void run() {
            LoggerUtil.printThread("开始获取素数");
            BigInteger p = BigInteger.ONE;
            while (!cancelled){
                //获取素数
                p = p.nextProbablePrime();
                synchronized (this){
                    LoggerUtil.printThread("素数:" + p);
                    primes.add(p);
                }
            }
        }

        public void cancel(){
            LoggerUtil.printThread("取消任务");
            this.cancelled = true;
        }

        public synchronized List<BigInteger> get(){
            return new ArrayList<>(primes);
        }
    }
}
